<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button id="connectButton" name="connectButton" class="buttonleft">
		  连接
		</button>
		<button
		  id="disconnectButton"
		  name="disconnectButton"
		  class="buttonright"
		  disabled>
		  断开
		</button>
		<div class="messagebox">
		  <label for="message"
		    >输入留言:
		    <input
		      type="text"
		      name="message"
		      id="message"
		      placeholder="Message text"
		      inputmode="latin"
		      size="60"
		      maxlength="120"
		      disabled />
		  </label>
		  <button id="sendButton" name="sendButton" class="buttonright" disabled>
		    发送
		  </button>
		</div>
		<div class="messagebox" id="receivebox">
		  <p>收到的信息:</p>
		</div>
		<script>
			(function() {
				let connectButton = null;
				let disconnectButton = null;
				let sendButton = null;
				let messageInputBox = null;
				let receiveBox = null;
				
				let localConnection = null; // RTCPeerConnection for our "local" connection
				let remoteConnection = null; // RTCPeerConnection for the "remote"
				
				let sendChannel = null; // RTCDataChannel for the local (sender)
				let receiveChannel = null; // RTCDataChannel for the remote (receiver)
				// 连接错误
				function handleCreateDescriptionError(error) {
				  console.log(`Unable to create an offer: ${error.toString()}`);
				}
				// 连接候选人成功
				function handleLocalAddCandidateSuccess() {
				  connectButton.disabled = true;
				}
				// 添加候选人失败
				function handleAddCandidateError() {
				  console.log("Oh noes! addICECandidate failed!");
				}
				// 数据管道
				function receiveChannelCallback(event) {
				  receiveChannel = event.channel;
				  receiveChannel.onmessage = handleReceiveMessage;
				  receiveChannel.onopen = handleReceiveChannelStatusChange;
				  receiveChannel.onclose = handleReceiveChannelStatusChange;
				}
				// 关闭处理
				function handleSendChannelStatusChange(event) {
				  if (sendChannel) {
				    const state = sendChannel.readyState;
				
				    if (state === "open") {
				      messageInputBox.disabled = false;
				      messageInputBox.focus();
				      sendButton.disabled = false;
				      disconnectButton.disabled = false;
				      connectButton.disabled = true;
				    } else {
				      messageInputBox.disabled = true;
				      sendButton.disabled = true;
				      connectButton.disabled = false;
				      disconnectButton.disabled = true;
				    }
				  }
				}
				// 连接状态修改
				function handleReceiveChannelStatusChange(event) {
				  if (receiveChannel) {
				    console.log(
				      `Receive channel's status has changed to ${receiveChannel.readyState}`,
				    );
				  }
				}
				// 发送信息
				function sendMessage() {
				  const message = messageInputBox.value;
				  sendChannel.send(message);
				
				  messageInputBox.value = "";
				  messageInputBox.focus();
				}
				// 接收信息
				function handleReceiveMessage(event) {
				  const el = document.createElement("p");
				  const txtNode = document.createTextNode(event.data);
				
				  el.appendChild(txtNode);
				  receiveBox.appendChild(el);
				}
				// 连接地址
				function connectPeers() {
					// 本地连接
					localConnection = new RTCPeerConnection();
					sendChannel = localConnection.createDataChannel("sendChannel");
					sendChannel.onopen = handleSendChannelStatusChange;
					sendChannel.onclose = handleSendChannelStatusChange;
					// 远程连接
					remoteConnection = new RTCPeerConnection();
					remoteConnection.ondatachannel = receiveChannelCallback;
					
					// 数据处理 添加候选人
					localConnection.onicecandidate = (e) =>
					  !e.candidate ||
					  remoteConnection.addIceCandidate(e.candidate).catch(handleAddCandidateError);
					
					remoteConnection.onicecandidate = (e) =>
					  !e.candidate ||
					  localConnection.addIceCandidate(e.candidate).catch(handleAddCandidateError);
						
					localConnection
					  .createOffer()
					  .then((offer) => localConnection.setLocalDescription(offer))
					  .then(() =>
					    remoteConnection.setRemoteDescription(localConnection.localDescription),
					  )
					  .then(() => remoteConnection.createAnswer())
					  .then((answer) => remoteConnection.setLocalDescription(answer))
					  .then(() =>
					    localConnection.setRemoteDescription(remoteConnection.localDescription),
					  )
					  .catch(handleCreateDescriptionError);

				}
				// 断开连接
				function disconnectPeers() {
				  // Close the RTCDataChannels if they're open.
				
				  sendChannel.close();
				  receiveChannel.close();
				
				  // Close the RTCPeerConnections
				
				  localConnection.close();
				  remoteConnection.close();
				
				  sendChannel = null;
				  receiveChannel = null;
				  localConnection = null;
				  remoteConnection = null;
				
				  // Update user interface elements
				
				  connectButton.disabled = false;
				  disconnectButton.disabled = true;
				  sendButton.disabled = true;
				
				  messageInputBox.value = "";
				  messageInputBox.disabled = true;
				}

				function startup() {
				  connectButton = document.getElementById("connectButton");
				  disconnectButton = document.getElementById("disconnectButton");
				  sendButton = document.getElementById("sendButton");
				  messageInputBox = document.getElementById("message");
				  receiveBox = document.getElementById("receivebox");
				
				  // 添加监听
				  connectButton.addEventListener("click", connectPeers, false);
				  disconnectButton.addEventListener("click", disconnectPeers, false);
				  sendButton.addEventListener("click", sendMessage, false);
				}
				startup();
			})();
		</script>
	</body>
</html>